/**
 * 服务
 * */
package org.zmhhxl.sample3.oauth2.a.service;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.zmhhxl.api.auth.RemoteUserInfoService;
import org.zmhhxl.api.auth.domain.entity.Role;
import org.zmhhxl.api.auth.domain.entity.UserInfo;
import org.zmhhxl.sample3.oauth2.a.authentications.model.CustomUserDetails;

import java.util.Optional;
import java.util.Set;

/**
 * 确认CustomOidcUserInfoService是否被正确注册
 * 并配置为UserDetailsService。
 * */
@Service
@Slf4j
public class CustomUserDetailsService /*extends InMemoryUserDetailsManager*/ implements UserDetailsService {

//   @Autowired
//   private UserDetailsService userDetailsService;   // CustomUserDetailsService

   // 创建密码编码器,
   PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

   @Autowired  //(required = true)  //ObjectProvider<
   private RemoteUserInfoService userInfoService /*= new UserInfoService()*/;

   // 显式打开session
//   @Autowired
//   private SessionFactory sessionFactory;

   @Override
   //@Transactional(readOnly = true) // 确保有活跃的Session
   public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
      log.info("调用接口UserDetailsService ======== {}",username);

      // 从数据库或其他数据源加载用户信息
      // 示例：从数据库加载用户
      //@Transactional(readOnly = true)
      Optional<UserInfo> user = userInfoService.findByUsername(username).getData();
      //Map<String, Object>  user1 = customOidcUserInfoService.(username).orElseThrow(() -> new UsernameNotFoundException("User not found with username: " + username));

      //return new InMemoryUserDetailsManager(user);
      // 添加用户权限，放入authorities，否则抛出意外错误
      if (user.isEmpty()){
         throw new UsernameNotFoundException("User not found with username: " + username);
      }

      UserInfo user1 = user.get();

      if(!user1.isEnabled()){
         throw new DisabledException("该账户已被禁用!");
      }

      if (user1.getPassword() == null) {
         user1.setPassword(passwordEncoder.encode("p"));
      }

      //
      //UserDetails user1 ;
      if (user1.getAuthorities() == null) {
          Role role = new Role();
              role.setRoleName("admin");
          user1.setAuthorities(Set.of(role));
      }

      //return user1;
       return new CustomUserDetails(user1); // 返回UserDetails的实现 UserInfo 必须进行Mixin序列化/反序列化
       //return (new InMemoryUserDetailsManager()).createUser(new CustomUserDetails(user1));
   }
}

//      else{
//         // 通过用户角色关联表查询对应的角色
//         List<SimpleGrantedAuthority> roles = user.get().getAuthorities().stream().map(role -> new SimpleGrantedAuthority(role.getAuthority())).toList();
//         //List<GrantedAuthority> roles = user.get().getAuthorities().stream().toList();
//         if (roles.isEmpty()) {
//             roles.add(new SimpleGrantedAuthority("USER1"));
//         }
//          user1 = User.withUsername(user.get().getUsername())
//                /**
//                 * 设置编码的方式, 默认是BCrypt
//                 * PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
//                 * 		return builder().passwordEncoder(encoder::encode);
//                 * */
//               .password(user.get().getPassword())  //passwordEncoder.encode(user.getPassword()
//               //.roles("USER1", "ADMIN1")  //调用new SimpleGrantedAuthority()增加到下面
//               // 有下面的，上面角色将被覆盖，授权就是角色(即字符串形式)
//               .authorities(roles)
//               .build();
//      }
